package cn.tedu.controller;

import cn.tedu.entity.CartItem;
import cn.tedu.entity.TAddress;
import cn.tedu.entity.TOrder;
import cn.tedu.entity.User;
import cn.tedu.service.TOrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author JokerQiu
 * @date 2021年12月23日 22:54
 */
@WebServlet("/createOrder")
public class CreateOrderServlet extends HttpServlet {
    private TOrderService orderService = new TOrderService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 用户是否登录
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 跳转登录页
            resp.sendRedirect("login.jsp");
        } else {
            // 下订单
            // 传递过来的地址信息、获取购物车信息
            TAddress address = new TAddress();
            address.setFullAddress(req.getParameter("fullAddress"));
            address.setMobile(req.getParameter("mobile"));
            address.setPhone(req.getParameter("phone"));
            address.setPostalCode(req.getParameter("postalCode"));
            address.setReceiveName(req.getParameter("receiveName"));
            address.setUserId(user.getId());

            Map<String, CartItem> cart = (Map<String, CartItem>) session.getAttribute("cart");

            TOrder order = orderService.createOrder(address, cart, user.getId());
            session.setAttribute("cart", null);
            session.setAttribute("order", order);
            resp.sendRedirect("order_ok.jsp");
        }
    }
}
